﻿using Blm.Utils.Extensions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using VisionCloud.Core.Model.Sys;
using VisionCloud.Domain.Common;
using VisionCloud.Domain.DtoModel.Sys;
using VisionCloud.Domain.Extension;
using VisionCloud.Domain.Repository.Interface.Sys;

namespace VisionCloud.Domain.Repository.Implement.Sys
{
    public class SysUserRoleRepository : BaseRepository<SysUserRole>, ISysUserRoleRepository
    {
        public async Task<List<SysUserRoleDto>> FindSysUserRole(Guid userId)
        {
            SysUserRoleCondition condition = new SysUserRoleCondition() { UserId = userId };
            var pageinfo = await GetPage(condition);
            return pageinfo.PageData as List<SysUserRoleDto>;
        }

        public async Task<SysUserRole> Get(SysUserRoleCondition condition)
        {
            var result = Query()
           .WhereIf(condition.UserId != Guid.Empty, w => w.UserId == condition.UserId)
           .WhereIf(condition.RoleId != Guid.Empty, w => w.RoleId == condition.RoleId)
           .WhereIf(condition.IsDeleted != false, w => w.IsDeleted == true)
           .Select(w => w.CopyTo<SysUserRole>())
           .DefaultOrderByDescending(condition, w => w.UserId)
           .FirstOrDefault();

            return result;
        }

        public async Task<ApiPageResult> GetPage(SysUserRoleCondition condition)
        {
            #region 下个版本修改

            var list = (from userRole in Db.SysUserRoles
                        join role in Db.SysRoles on userRole.RoleId equals role.RoleId
                        join user in Db.SysUsers on userRole.UserId equals user.YunUserGuid
                        where condition.UserId == Guid.Empty || condition.UserId == user.YunUserGuid
                        select new SysUserRoleDto()
                        {
                            RoleId = role.RoleId,
                            RoleName = role.Name,
                            UserName = user.Name,
                            UserId = user.YunUserGuid,
                            UserRoleId = userRole.UserRoleId
                        }
                      ).ToList().OrderBy(p => p.UserId).ToList();

            #endregion 下个版本修改

            var result = condition.CopyTo<ApiPageResult>();
            result.PageData = list;
            return result;
        }
    }
}